// import { collect } from './collecct'
// import { upload } from './upload'
// import qs from 'qs';

// 钩子函数
// 参数创建前
let beforeCreateParams;
// 上报日志前
let beforeUpload;
// 上报日志后
let afterupload;
// 异常处理
let onError = function(e) {
  console.log('默认打印异常信息', e);
};

function upload(params) {
  console.log('upload..', params);
  let data = params.toString();
  if (Object.prototype.toString.call(params) === '[object Object]') {
    const list = [];
    Object.entries(params).forEach(item => {
      list.push(`${item[0]}=${item[1]}`);
    })
    if (list.length > 0) {
      data = list.join('&');
    }
  }
  let image = new Image();
  // TODO 上报接口 api 地址
  const src = `https://www.imooc.com?${data}`;
  image.src = src;
  image = null;

  return {
    url: src,
    data: params,
  }
}

function collect() {
  console.log('collect');
  sendPV()
}

/**
 * 采集基本信息：注册进入或者再页面的meta信息中写死
 *    应用id：应用在 meta 属性 zy-app-id
 *    页面id：页面在 body 属性 zy-page-id，或者通过路由获取
 * 日志上报信息：
 *    应用id和页面id
 *    访问时间
 *    ua
 * 日志上报API
 *    upload中实现上报API
 */
function sendPV() {
  beforeCreateParams && beforeCreateParams();
  // 采集页面基本信息
  let appId = '', pageId = '';
  const metaList = document.getElementsByTagName('meta');
  metaList
  for(const meta of metaList) {
    console.log(meta);
    if (meta.getAttribute('zy-app-id')) {
      appId = meta.getAttribute('zy-app-id');
      break;
    }
  }
  pageId = document.body.getAttribute('zy-page-id') || '';
  const timestampe = new Date().getTime();
  const ua = window.navigator.userAgent;
  console.log(appId, pageId, timestampe, ua);
  let params = {
    appId, pageId, timestampe, ua, eventType: 'PV',
  }
  if (beforeUpload) {
    const res = beforeUpload(params);
    if (res) {
      params = res;
    }
  }
  let url = '', data = {};
  try {
    const res = upload(params);
    url = res.url;
    data = res.data;
    throw new Error('手动抛出异常');
  } catch(e) {
    onError(e);
  } finally {
    afterupload && afterupload(url, data);
  }
}

// 参数创建前
function registerBeforeCreateParams(fn) {
  beforeCreateParams = fn;
}
// 上报日志前
function registerBeforeUpload(fn) {
  beforeUpload = fn;
}
// 上报日志后
function registerAfterupload(fn) {
  afterupload = fn;
}
// 异常处理
function registerOnError(fn) {
  onError = fn;
}

window.ZyCliMonitor = {
  collect,
  upload,
  registerBeforeCreateParams,
  registerBeforeUpload,
  registerAfterupload,
  registerOnError,
}